<template>
	<view class="p-10">
		<u-navbar back-text="返回" title="商品评论"></u-navbar>
		<hd-loading v-if="loading"/>
		<view class="mt-30" v-if="comments.length">
			<view v-for="comment in comments" :key="comment.id" class="inline-block mb-30 px-10 w-full">
				<hd-comment-item :goods="goods" :comment="comment" :showReply="true">
					<template #right>
						<view class="" @click="reply(comment.id)">
							回复
						</view>
					</template>
				</hd-comment-item>
			</view>
		</view>
	<!-- 	<view class="flex items-center justify-center p-30" v-if="isEnd">
			没有新评论了
		</view> -->

		<!-- 评论或回复 -->
		<u-popup v-model="commentBoxShow" mode="bottom" :mask="true" :border-radius="5">
			<view class="p-50">
				<view class="mb-20">
					<u-input type="textarea" v-model="form.content" border class="mb-30" />
				</view>
				<u-button type="error" class="mt-20" @click="onSubmit">发表</u-button>
			</view>
		</u-popup>
		<view class="p-20 rounded-full shadow-md w-50 h-50 flex justify-center items-center"
			style="position: fixed;bottom: 150rpx;right:30rpx;background-color: #333;color:white;"
			@click="reply(null)">
			发表
		</view>
		<hd-tabbar></hd-tabbar>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				goods: null,
				comments: [],
				page: 1,
				//评论全部加载
				isEnd: false,
				//评论弹出层显示
				commentBoxShow: false,
				loading: true,
				form: {
					content: '',
					comment_id: null
				}
			}
		},
		async onReachBottom() {
			this.loadComments()
		},
		async onLoad(options) {
			this.goods = await this.$api.get(`goods/${options.gid}`)
			await this.loadComments()
			this.loading = false
		},
		methods: {
			//加载评论
			async loadComments() {
				if(this.isEnd) return;
				let res = await this.$api.get(`goods/${this.goods.id}/comment?page=${this.page++}`)
				if (!res.data.length) {
					uni.showToast({
						title:'已全部加载'
					})
					return this.isEnd = true
				}
				this.comments.push(...res.data)
			},
			//显示回复表单
			reply(comment_id) {
				this.form.content = '';
				this.form.comment_id = comment_id;
				this.commentBoxShow = true
			},
			//发表评论
			async onSubmit() {
				this.$api.post(`goods/${this.goods.id}/comment`, this.form).then(res => {
					uni.showToast({
						title: '评论发表成功'
					})
					
					//隐藏发表评论弹出层
					this.commentBoxShow = false

					if (res.comment_id) {
						const comment = this.comments.find(m => m.id == res.comment_id)
						comment.replys.unshift(res)
					} else {
						this.comments.unshift(res)
					}
				}).catch(_ => {

				})
			}
		}
	}
</script>

<style>

</style>
